package com.yunshipei.inter.JsInterface;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;

import com.yunshipei.common.Globals;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.YspEvent.HomeFragmentEvent;
import com.yunshipei.ui.fragment.HomeFragment;

import java.util.List;

import io.rong.eventbus.EventBus;
import okhttp3.Cookie;

public class BaseHomeJsObject {

    protected Handler handler;

    public BaseHomeJsObject() {
        handler = new Handler(Looper.getMainLooper());
    }

    @org.xwalk.core.JavascriptInterface
    public String getCookie() {
        List<Cookie> cookies = EnterClient.getInstances().getManagerCookies();
        String cookieStr = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieStr = cookie.name() + "=" + cookie.value() + ";domain=" + cookie.domain();
            }
        }
        return cookieStr;
    }

    @org.xwalk.core.JavascriptInterface
    public void modifyDataJs(final String dataJs, final boolean shouldRefresh) {
        handler.post(new Runnable() {
            @SuppressLint("CommitPrefEdits")
            @Override
            public void run() {
                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_DATA_JS, dataJs).commit();
                if (!shouldRefresh) return;
                EventBus.getDefault().post(new HomeFragmentEvent(HomeFragment.URL_TYPE_REFRESH));
            }
        });
    }
}
